package com.tiantian.quanminxiu.wxapi;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.shenglian.utils.utils.CommonUtils;
import com.shenglian.utils.utils.ImageUtils;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tiantian.quanminxiu.api.AnchorService;
import com.tiantian.quanminxiu.api.WeiXinService;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.ApplicationBase;
import com.tiantian.quanminxiu.utils.Constants;
import com.tiantian.quanminxiu.utils.UserData;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ntop on 15/9/4.
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {


    static IWXAPI iwxapi;
    private static WXEntryBackCall wxEntryBackCall;
    public String nickname = "";
    public String unionid = "";
    public String wxcode = "";
    public String openid = "";
    public String access_token = "";
    public String refresh_token = "";
    public String expires_in = "";
    public String sex;
    public static int isLogin = 0;// 判断是登录还是分享 0登录 1分享

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(iwxapi==null){
            finish();
            return;
        }else {
            iwxapi.handleIntent(getIntent(), WXEntryActivity.this);
        }
    }

    public static void startWXlogin(Context context,WXEntryBackCall backCall) {
        // 注册微信
        if (iwxapi == null) {
            iwxapi = WXAPIFactory.createWXAPI(context, ApplicationBase.Weixin_AppId, true);
            iwxapi.registerApp(ApplicationBase.Weixin_AppId);
        }
        if (!iwxapi.isWXAppInstalled() && iwxapi.isWXAppSupportAPI()) {
            CommonUtils.showToask(context, "请先安装微信客户端");
            return;
        }
        isLogin = 0;
        wxEntryBackCall = backCall;
        // 发送登录
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "4189496as4d984";
        iwxapi.sendReq(req);
    }

    //region 分享页面 APPShare（）
    public static void APPShare(Context context,String title,int roomId,String anchorName ,int shareType) {
        if (iwxapi == null) {
            iwxapi = WXAPIFactory.createWXAPI(context, ApplicationBase.Weixin_AppId, true);
            iwxapi.registerApp(ApplicationBase.Weixin_AppId);
        }
        if (!iwxapi.isWXAppInstalled() && iwxapi.isWXAppSupportAPI()) {
            CommonUtils.showToask(context, "请先安装微信客户端");
            return;
        }
        isLogin = 1;
        iwxapi.registerApp(ApplicationBase.Weixin_AppId);
        WXMediaMessage msg = new WXMediaMessage();
        SendMessageToWX.Req req = new SendMessageToWX.Req();

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = ApplicationBase.downAppUrl;    //分享链接
        req.transaction = ("webpage" == null) ? String.valueOf(System.currentTimeMillis()) : "webpage" + System.currentTimeMillis();

        msg.mediaObject = webpage;

        if(shareType==0){
            msg.title = "全民秀做全民参与的直播平台~";
        }else {
            msg.title = "全民秀做全民参与的直播平台~~你的好友《"+anchorName+"》正在全民秀直播["+title+"]";
        }

        msg.description = "你的好友《"+anchorName+"》正在全民秀直播["+title+"]";

        ImageLoader.getInstance().loadImage(APPUtils.createUserCover(roomId), new ImageSize(100, 100), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                try {
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(loadedImage, 100, 100, true);
                    loadedImage.recycle();
                    msg.thumbData = ImageUtils.Bitmap2Bytes(thumbBmp);
                } catch (Exception e) {
                }
                req.message = msg;
                switch (shareType) {
                    case 0://发送到好友
                        req.scene = SendMessageToWX.Req.WXSceneSession;
                        break;
                    case 1://00
                        req.scene = SendMessageToWX.Req.WXSceneTimeline;
                        break;
                    default:
                        return;
                }
                iwxapi.sendReq(req);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });
    }
    //endregion

    @Override
    public void onReq(BaseReq baseReq) {
        finish();
    }

    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if(isLogin==0){
                    wxcode = ((SendAuth.Resp) baseResp).code;
                    WeiXinService weiXinService = WeiXinService.Factory.create();
                    weiXinService.access_token(ApplicationBase.Weixin_AppId, ApplicationBase.Weixin_appSecret, wxcode, "authorization_code")
                            .flatMap(str -> {
                                try {
                                    String strValue = str.string();
                                    Log.i("dd", "--weentry:" + strValue);
                                    JSONObject jsonObject = new JSONObject(strValue);
                                    openid = jsonObject.getString("openid").toString().trim();
                                    access_token = jsonObject.getString("access_token").toString().trim();
                                    unionid = jsonObject.getString("unionid").toString().trim();
                                    refresh_token = jsonObject.getString("refresh_token").toString().trim();
                                    expires_in = jsonObject.getString("expires_in").toString().trim();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                return weiXinService.userinfo(access_token, openid);
                            })
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeOn(Schedulers.newThread())
                            .subscribe(str -> {
                                Log.i("dd", "--weeuser_userinfo_info:" + str.toString());
                                //登录成功,跳转到首页
                                try {
                                    String strValue = str.string();
                                    Log.i("dd", "--weentry:" + strValue);
                                    JSONObject jsonObject = new JSONObject(strValue);
                                    nickname = jsonObject.getString("nickname");
                                    unionid = jsonObject.getString("unionid");
                                    sex = jsonObject.getString("sex");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if(wxEntryBackCall!=null){
                                    wxEntryBackCall.backcall(openid, unionid,access_token,
                                            expires_in, refresh_token, nickname, sex);
                                    finish();
                                }else {
                                    throw new RuntimeException("wxEntryBackCall接口为空");
                                }
                            }, throwable -> {
                                CommonUtils.showToask(this,"微信登录失败:"+throwable.getMessage());
                                finish();
                            });
                }else {
                    CommonUtils.showToask(this,"分享成功");
                    ApplicationBase app = ApplicationBase.get(this);
                    AnchorService anchorService = app.getAnchorService();
                    anchorService.share(UserData.Current.mid, Constants.APP_TYPE,UserData.Current.sign,0)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeOn(app.defaultSubscribeScheduler())
                            .subscribe(str -> {
                                CommonUtils.showToask(this,str.optString("msg"));
                                UserData.Reload.Fragment_Mine = true;
                                UserData.Base.Coin += 5;
                                finish();
                            }, throwable -> {
                                finish();
                            });

                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Log.e("微信登录", "取消微信登录");
                if (wxEntryBackCall!=null) {
                    wxEntryBackCall.onError("取消微信登录");
                }
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Log.e("微信登录", "授权失败");
                if (wxEntryBackCall!=null) {
                    wxEntryBackCall.onError("授权失败");
                }
                finish();
                break;
            default:
                if (wxEntryBackCall!=null) {
                    wxEntryBackCall.onError("授权失败");
                }
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iwxapi = null;
        wxEntryBackCall=null;
    }

    public interface WXEntryBackCall{
        void backcall(String openid ,String unionid, String access_token,String expires_in,String refresh_token,String nickname,String sex);
        void onError(String msg);
    }
}
